<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      ref="formRef"
      :model="formData"
      label-width="0"
    >
      <el-row style="margin-bottom: 10px " align="bottom">
        <p style="font-weight: bold">粘贴文本</p>
        <p style="margin-left: 10px; font-size: 12px; text-decoration: underline; cursor: pointer" @click="copyContentMethod">点击复制模板</p>
      </el-row>
      <el-row style=" border: 1px solid #999;" type="flex" class="row-bg" justify="center" align="top">
        <el-col :span="leftSpan" class="no-border">
          <el-input type="textarea" v-model="formData.content" :placeholder="copyContent" :autosize="{ minRows: 12, maxRows: 24}" />
        </el-col>
        <el-col :span="rightSpan">
          <el-row type="flex" class="row-bg" justify="center" style="padding: 10px">
            <el-col :span="24">智能审核<el-divider style="margin: 5px 0"/></el-col>
            <el-col :span="24">
              <el-row type="flex" class="row-bg" align="bottom">
                <h3 style="margin-right: 15px">{{formSubResult?.dataQueryDO?.queryName}}</h3>
                <span style="font-size: 14px">{{formSubResult?.dataQueryDO?.validGender}} | {{formSubResult?.dataQueryDO?.validAge}} 岁</span>
                <span style="font-size: 14px; margin-left: 20px">
                  {{formSubResult?.dataQueryDO?.queryIdCard}}
                  <Icon @click="copyIdCardMethod" icon="ep:document-copy" class="ml-5px w-full h-full text-[#1E90FF]" />
                </span>
              </el-row>
              <el-row type="flex" class="row-bg mt-10px" align="bottom">
                <p v-if="formSubResult?.dataQueryDO?.validAddress" style="margin-right: 15px; font-size: 14px">{{formSubResult?.dataQueryDO?.validAddress}}</p>
                <el-tag v-if="formSubResult?.dataQueryDO?.validAddressType" size="small">{{formSubResult?.dataQueryDO?.validAddressType}}</el-tag>
              </el-row>
              <el-row type="flex" class="row-bg" justify="center" style="border: 1px solid #bfcbd9; margin-top: 10px">
                <el-col :span="6" style="text-align: center; padding: 5px; font-size: 13px; background: #f0f2f5">撸子分析</el-col>
                <el-col :span="6" style="text-align: center; padding: 5px; font-size: 13px; background: #f0f2f5">证件二要素</el-col>
                <el-col :span="6" style="text-align: center; padding: 5px; font-size: 13px; background: #f0f2f5">探查结果</el-col>
                <el-col :span="6" style="text-align: center; padding: 5px; font-size: 13px; background: #f0f2f5">履约笔数</el-col>
                <el-col :span="6" style="text-align: center; padding: 5px; font-size: 13px">
                  <p v-if="formSubResult?.dataQueryDO?.riskType === 1" style="color: #2bb673; font-size: 13px">安全客户</p>
                  <p v-else style="font-size: 13px">
                    <span style="color: red;">{{formSubResult?.dataQueryDO?.riskType === 2 ? '撸子' : '疑似撸'}}</span>
                    <el-popover
                      placement="bottom"
                      width="700"
                      trigger="click">
                      <el-table :data="lzList" style="height: 280px">
                        <el-table-column label="姓名" align="center" prop="name" />
                        <el-table-column label="手机号" align="center" prop="mobile" />
                        <el-table-column label="身份证" align="center" prop="idCard" min-width="160"/>
                        <el-table-column label="用户类型" align="center" prop="type" />
                        <el-table-column label="查询次数" align="center" prop="queryCount" />
                      </el-table>
                      <template #reference>
                        <span>(<span style="cursor: pointer; color: #2d8cf0">{{formSubResult?.dataQueryDO?.riskTypeFinanceIds.length}}</span>)</span>
                      </template>
                    </el-popover>
                  </p>
                </el-col>
                <el-col :span="6" style="text-align: center; padding: 5px; font-size: 13px">
                  <el-tag type="info" v-if="formSubResult?.dataQueryDO?.vaildResult === 0">未校验</el-tag>
                  <el-tag type="success" v-if="formSubResult?.dataQueryDO?.vaildResult === 1">一致</el-tag>
                  <el-tag type="danger" v-else>不一致</el-tag>
                </el-col>
                <el-col :span="6" style="text-align: center; padding: 5px; font-size: 13px">
                  <el-tag type="danger" v-if="formSubResult?.dataQueryTanzcDO?.resultCode === '1'">逾期未还款</el-tag>
                  <el-tag type="success" v-if="formSubResult?.dataQueryTanzcDO?.resultCode === '2'">正常履约</el-tag>
                  <el-tag type="warning" v-else>未知</el-tag>
                </el-col>
                <el-col :span="6" style="text-align: center; padding: 5px; font-size: 13px">
                  <el-tag v-if="formSubResult?.dataQueryTanzcDO?.countPerformance" type="success">{{formSubResult?.dataQueryTanzcDO?.countPerformance}}</el-tag>
                  <el-tag v-else type="info">暂无</el-tag>
                </el-col>
                <el-col :span="6" style="text-align: center; padding: 5px; font-size: 13px; background: #f0f2f5">最大履约金额</el-col>
                <el-col :span="6" style="text-align: center; padding: 5px; font-size: 13px; background: #f0f2f5">最近履约时间</el-col>
                <el-col :span="6" style="text-align: center; padding: 5px; font-size: 13px; background: #f0f2f5">最大逾期金额</el-col>
                <el-col :span="6" style="text-align: center; padding: 5px; font-size: 13px; background: #f0f2f5">逾期机构数</el-col>
                <el-col :span="6" style="text-align: center; padding: 5px; font-size: 13px">
                  <el-tag v-if="formSubResult?.dataQueryTanzcDO?.maxPerformanceAmt" type="success">{{formSubResult?.dataQueryTanzcDO?.maxPerformanceAmt}}</el-tag>
                  <el-tag v-else type="info">暂无</el-tag>
                </el-col>
                <el-col :span="6" style="text-align: center; padding: 5px; font-size: 13px">
                  <el-tag v-if="formSubResult?.dataQueryTanzcDO?.latestPerformanceTime" type="success">{{formSubResult?.dataQueryTanzcDO?.latestPerformanceTime}}</el-tag>
                  <el-tag v-else type="info">暂无</el-tag>
                </el-col>
                <el-col :span="6" style="text-align: center; padding: 5px; font-size: 13px">
                  <el-tag v-if="formSubResult?.dataQueryTanzcDO?.maxOverdueAmt" type="success">{{formSubResult?.dataQueryTanzcDO?.maxOverdueAmt}}</el-tag>
                  <el-tag v-else type="info">暂无</el-tag>
                </el-col>
                <el-col :span="6" style="text-align: center; padding: 5px; font-size: 13px">
                  <el-tag v-if="formSubResult?.dataQueryTanzcDO?.currentlyOverdue" type="success">{{formSubResult?.dataQueryTanzcDO?.currentlyOverdue}}</el-tag>
                  <el-tag v-else type="info">暂无</el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-form>
    <el-row style="margin-top: 10px" type="flex" class="row-bg" justify="center" align="center" >
      <el-button @click="submitForm" :disabled="submitFormDisabled" type="primary">{{ '智能审核（' + zndbApiPrice + '元/次）'}}</el-button>
<!--      <el-button>重 置</el-button>-->
    </el-row>
  </ContentWrap>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="姓名" prop="queryName">
        <el-input
          v-model="queryParams.queryName"
          placeholder="请输入姓名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
        row-key="id"
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        @selection-change="handleRowCheckboxChange"
    >
      <el-table-column
        type="index"
        width="50"/>
      <el-table-column label="姓名" align="center" prop="queryName" />
      <el-table-column label="身份证号" align="center" prop="queryIdCard" />
      <el-table-column
        label="查询时间"
        align="center"
        prop="queryTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="showDetail(scope.row.id)"
            v-hasPermi="['business:info-audit:query']"
          >
            查看
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['business:info-audit:delete']"
          >
            删除数据库
          </el-button>
          <el-button
            v-if="scope.row.auditIsBlacklist === false"
            link
            type="primary"
            @click="addBlackList(scope.row.id)"
            v-hasPermi="['business:info-audit:delete']"
          >
            加入黑名单
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import { DataQueryApi, DataQuery } from '@/api/business/dataquery'
import { ApiTypeInfoApi, ApiTypeInfo } from '@/api/business/apitypeinfo'
import { TfFinanceApi, TfFinance } from '@/api/business/tffinance'
import {ContentWrap} from "@/components/ContentWrap";
import {Icon} from "@/components/Icon";
import {BizConfigApi} from "@/api/business/config";

/** 智能比对 列表 */
defineOptions({ name: 'InfoAudit' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<DataQuery[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  queryName: undefined,
  userId: undefined,
  deptId: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单

const route = useRoute() // 路由
const router = useRouter() // 路由

/** 查详情 */
const showDetail = async (id:number) => {
  router.push({
    name: 'InfoAuditDetail',
    query: { id }
  })
}

/** 加入黑名单 */
const addBlackList = async (id:number) => {
  let remark = await message.promptCustom("确认加入黑名单吗？", "提示")
  await DataQueryApi.addBlacklist(id, remark.value)
  message.success(t('common.success'))
  getList()
}

const lzList = ref() // 搜索的表单
/** 获取撸子 */
const getLz = async () => {
  let ids = formSubResult.value?.dataQueryDO?.riskTypeFinanceIds;
  if (ids && ids.length > 0) {
    let data = {ids: formSubResult.value?.dataQueryDO?.riskTypeFinanceIds}
    lzList.value = await TfFinanceApi.getTfFinancesByIds(data)
  }
}


const zndbApiPrice = ref()

/** 查询列表 */
const getZndbApi = async () => {
  zndbApiPrice.value = await ApiTypeInfoApi.getApiZnshPrice()
}

let copyContent = ref('【申请额度】：\n' +
  '【联系方式】：\n' +
  '【姓名】：\n' +
  '【身份证号】：\n' +
  '【合作财务】：\n' +
  '【现居住地】：\n' +
  '【户籍所在地】：\n' +
  '【芝麻分】：\n' +
  '【能否接受腾讯会议】：')
const getCopyContent = async () => {
  copyContent.value = (await BizConfigApi.getBizConfig(6)).value
}

const copyContentMethod = async () => {
  navigator.clipboard.writeText(copyContent.value)
  message.success('复制成功')
}
const copyIdCardMethod = async () => {
  navigator.clipboard.writeText(formSubResult.value?.dataQueryDO?.queryIdCard)
  message.success('复制成功')
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await DataQueryApi.getDataQueryPageAudit(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await DataQueryApi.deleteDataQueryAudit(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: DataQuery[]) => {
  checkedIds.value = records.map((item) => item.id);
}

const formData = ref({
  content: undefined,
})
const formRef = ref() // 表单 Ref

const formSubResult = ref();

let leftSpan = ref(24)
let rightSpan = ref(0)

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

let submitFormDisabled = ref(false)
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  try {
    submitFormDisabled.value = true
    formSubResult.value = await DataQueryApi.createDataQueryAudit(formData.value)
    leftSpan.value = 12
    rightSpan.value = 12
    message.success(t('common.success'))
    // 发送操作成功的事件
    emit('success')
    await getLz()
  } finally {
    getList()
    submitFormDisabled.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    userId: undefined,
    deptId: undefined,
    name: undefined,
    mobile: undefined,
    result: undefined,
    queryTime: undefined,
  }
  formRef.value?.resetFields()
}

/** 初始化 **/
onMounted(() => {
  resetForm()
  getList()
  getZndbApi()
  getCopyContent()
})
</script>

<style scoped>
.no-border>>>.el-textarea__inner {
  border: 0; /* 去掉边框 */
  outline: none; /* 去掉聚焦时的外边框 */
  resize: none;
}
</style>
